package kz.kstu.scantest.business.client.key;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import kz.kstu.scantest.business.entity.Key;
import kz.kstu.scantest.business.util.DateUtil;
import kz.kstu.scantest.business.util.DigestUtil;
import kz.kstu.scantest.business.util.logger.Logger;

import java.io.UnsupportedEncodingException;

/**
 * @author Filipp_Stankevich
 *         created 02.09.12 8:25
 */
public class KeyDigestWorker {

    private final static Logger LOGGER = Logger.getLogger(KeyDigestWorker.class);

    public void digest (Key key) {
        String digest = createBase64Digest(key);
        key.setDigest(digest);
    }

    public boolean validate(Key key) {
        String digest = createBase64Digest(key);
        return digest.equals(key.getDigest());
    }

    private String createBase64Digest(Key key) {
        byte[] data = getDataForDigest(key);
        byte[] digest = DigestUtil.digestByte(data, DigestUtil.ALGORITHM_SHA);
        return Base64.encode(digest);
    }

    private byte[] getDataForDigest(Key key) {
        StringBuilder builder = new StringBuilder();

        builder.append(key.getNumber());
        builder.append(String.valueOf(key.getWriteOffCount()));
        builder.append(String.valueOf(key.getMaxCount()));
        builder.append(DateUtil.formatDate(key.getExpiryDate(), DateUtil.SIMPLE_DATE_PATTERN));

        String message =  builder.toString();
        byte[] data = null;
        try {
            data = message.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return data;
    }
}
